package cn.jhc.dao;

import cn.jhc.entity.Book;
import cn.jhc.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface BookDAO {
    @Insert("insert into t_book(name,price,author,sales,stock,img_path) values(#{name},#{price},#{author},#{sales},#{stock},#{imgPath})")
    @SelectKey(statement = "select last_insert_id()",keyProperty = "bookId",before = false,resultType = Integer.class)
    public int save(Book book);

    @Update({"<script>",
            "update t_book",
            "  <set>",
            "    <if test='name != null'>name=#{name},</if>",
            "    <if test='price != null'>price=#{price},</if>",
            "    <if test='author != null'>author=#{author},</if>",
            "    <if test='sales != null'>sales=#{sales},</if>",
            "    <if test='stock != null'>stock=#{stock},</if>",
            "    <if test='imgPath != null'>img_path=#{imgPath},</if>",
            "  </set>",
            "where book_id=#{bookId}",
            "</script>"})
    public int update(Book book);

    @Delete("delete from t_book where book_id=#{bookId}")
    public int delete(Integer bookId);

    @Select("select * from t_book where book_id=#{bookId}")
    public Book queryOne(Integer bookId);

    @Select({"<script>",
            "select * from t_book",
            "  <where>",
            "    <if test='name != null'>name like '%${name}%'</if>",
            "    <if test='price != null'>price=#{price}</if>",
            "    <if test='author != null'>author like '%${author}%'</if>",
            "    <if test='sales != null'>sales=#{sales}</if>",
            "    <if test='stock != null'>stock=#{stock}</if>",
            "    <if test='imgPath != null'>img_path like '%${imgPath}%'</if>",
            "  </where>",
            "</script>"})
    public List<Book> query(Book book);

    @Select("select * from t_book where book_id=#{bookId}")
    @Results(id="bookMap",value = {
            @Result(property = "bookId",column = "book_id"),
            @Result(property = "name",column = "name"),
            @Result(property = "price",column = "price"),
            @Result(property = "author",column = "author"),
            @Result(property = "sales",column = "sales"),
            @Result(property = "stock",column = "stock"),
            @Result(property = "imgPath",column = "img_path"),
            @Result(property = "items",column = "book_id",
                    many = @Many(select = "cn.jhc.dao.ItemDAO.QueryByBook",fetchType = FetchType.LAZY))
    })
    public Book findBookItems(Integer bookId);



}
